<?php

namespace App\Services;

use GuzzleHttp\Client;

class MPay
{
    static function pay($outNo, $amount, $subject)
    {
        $url = 'https://wa.yaomeban.xyz/api/pay';
        $client = new Client();
        $resp = $client->post($url, [
            'form_params' => [
                'out_no' => $outNo,
                'amount' => $amount,
                'notify_url' => url('/notify/mpay'),
                'desc' => $subject

            ]
        ]);
        return self::data($resp);
    }

    static function info($sn)
    {
        $url = 'https://wa.yaomeban.xyz/api/pay_info/' . $sn;
        $client = new Client();
        $resp = $client->get($url);
        return self::data($resp);
    }

    static protected function data($resp)
    {
        if ($resp->getStatusCode() === 200) {
            $content = $resp->getBody()->getContents();
            $arr = json_decode($content, true);
            $code = $arr['code'] ?? 500;
            $data = $arr['data'] ?? '';

            if ($code == 200 && $data) {
                return $data;
            }
            $msg = $arr['msg'] ?? '未知错误';
            abort(500, $msg);
        }
        abort(500, '请求支付发生未知错误');
    }
}
